package com.firstsource.networking.ip.tracker.data.access;

import java.util.ArrayList;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import com.firstsource.networking.ip.tracker.data.HibernateUtil ;
import com.firstsource.networking.ip.tracker.data.entities.Host;
import com.firstsource.networking.ip.tracker.util.IPManipulator;

public class HostDAO {

	private Session session = null ;

	public HostDAO() {
		session = HibernateUtil.currentSession() ;
	}

	public void saveOrUpdate(Host currHost) {
		session.beginTransaction() ;
		session.save(currHost) ;
		session.getTransaction().commit() ;
	}

	public Host getHostByIp(String ipAddr) {

		long longIp = IPManipulator.ip2Long(ipAddr) ;
		
		session.beginTransaction() ;
		Host retVal = (Host)session.createQuery("From Host where ipAddr=:address").setLong(0, longIp).list().get(0) ;
		session.getTransaction().commit() ;

		return retVal;
	}

	@SuppressWarnings("unchecked")
	public ArrayList<Host> getHostsBySubnet(String network, String netmask) {
		long allOnes = IPManipulator.ip2Long("255.255.255.255") ;
		long net = IPManipulator.ip2Long(network) ;
		long mask = IPManipulator.ip2Long(netmask) ;
		long max = net + (allOnes - mask) ;
		session.beginTransaction() ;
		ArrayList<Host> retVal = (ArrayList)session.createQuery("From Host where ipAddr >= :network and ipAddr <= :broadcast").setLong("network", net).setLong("broadcast", max).list() ;
		return retVal ;
	}

	@SuppressWarnings("unchecked")
	public ArrayList<Host> getHostsByRange(String start, String end) {
		long low, high ;
		low = IPManipulator.ip2Long(start) ;
		high = IPManipulator.ip2Long(end) ;
		session.beginTransaction() ;
		ArrayList<Host> retVal = (ArrayList)session.createQuery("From Host where ipAddr >= :network and ipAddr <= :broadcast").setLong("network", low).setLong("broadcast", high).list() ;
		return retVal ;
	}

	@SuppressWarnings("unchecked")
	public ArrayList<Host> getHostsName(String name) {
		session.beginTransaction() ;
		Criteria crit = session.createCriteria(Host.class) ;
		crit.add(Restrictions.ilike("hostname", "%"+name+"%")) ;
		ArrayList<Host> retVal = (ArrayList)crit.list() ;
		session.getTransaction().commit() ;
		return retVal ;
	}	
}
